package processor
{
	import events.ClockEvent;
	
	import flash.events.Event;
	import flash.utils.getTimer;
	
	import mx.core.UIComponent;
	
	[Event(name="clockTick",type="events.ClockEvent")]
	
	public class Clock extends UIComponent
	{
		
		[Bindable]
		public var tempo:int;
		
		[Bindable]
		public var steps:int;
		
		private var currentStep:int;
		private var msEachStep:Number;
		private var msInitial:Number;
		
		public function Clock()
		{
		}
		
		public function start():void
		{
			if( !hasEventListener( Event.ENTER_FRAME ) )
			{
				msInitial = null;
				currentStep = 1;
				dispatchEvent( new ClockEvent( ClockEvent.CLOCK_TICK, currentStep ) );
				addEventListener( Event.ENTER_FRAME, handleEnterFrame );
			}
		}
		
		public function stop():void
		{
			if( hasEventListener( Event.ENTER_FRAME ) )
			{
				removeEventListener( Event.ENTER_FRAME, handleEnterFrame );
			}
				
		}
		
		protected function handleEnterFrame( event:Event=null ):void
		{
			var time:int = getTimer();
			msEachStep = 15000 / tempo;
			if( !msInitial )
				msInitial = time;
			
			if( time - msInitial >= msEachStep )
			{
				if( currentStep == steps )
					currentStep = 1
				else
					currentStep++;
				
				dispatchEvent( new ClockEvent( ClockEvent.CLOCK_TICK, currentStep ) );
				msInitial = null;
			}
			
		}

	}
}